<?php

namespace Api\Event;


/** 
 * 关注接口
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class FollowEvent extends BaseEvent 
{


	/** 
	 * 是否关注  
	 * @author Legend. <xcx_legender@qq.com>
	 * @param $uid 是否关注了 $target_id
	 * @return 
	 */
	
	public function is_follow($uid, $target_id)
	{
		$map['uid'] 	  = intval($uid);
		$map['target_id'] = intval($target_id);
		return D('Common/Follow', 'Service')->where($map)->count() > 0;
	}


	/** 
	 * 我的关注总数
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function count_mine($uid)
	{
		$map['uid'] 	  = intval($uid);
		return D('Common/Follow', 'Service')->where($map)->count();
	}

	/** 
	 * 我的粉丝总数
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function count_follows($uid)
	{
		$map['target_id'] 	  = intval($uid);
		return D('Common/Follow', 'Service')->where($map)->count();
	}

	
	/** 
	 * 获取我的关注信息
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 int $uid; 
	 boolen just_ids : 是否只取得id数组 
	 * @return 
	 */
	//susy add param $page 分页的页数, 默认不分页 2015/5/14
	public function mine($uid, $detail = false, $query = array(), $limit = 10, $page=0)
	{
		$uid = intval($uid);
		$service = D('Common/Follow', 'Service');
		$map['uid'] = $uid;
		$query && $map = array_merge($map, $query);

		//start modiby by susy
		//$mine_uids = $service->order('create_time desc')->where($map)->limit($limit)->getField('target_id', true);
		$res = $service->order('create_time desc')->where($map)->limit($limit);
		if($page)
			$res = $res->page($page);
		$mine_uids = $res->getField('target_id', true);
		//end
		if (!$detail)
		{
			return $mine_uids;
		}
		else
		{
			$uEvent = A('Api/User','Event');
			foreach ($mine_uids as $id) {
				$user = $uEvent->detail($id);
				$user['is_follow'] = $this->is_follow($id, $uid);
				$data[] = $user;
			}
			return $data;
		}
	}


	/** 
	 * 获取关注我的人的信息
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	//susy add param $page 分页的页数, 默认不分页 2015/5/14
	public function follows($uid, $detail = false, $query = array(), $limit = 10, $page=0)
	{
		$uid = intval($uid);
		$service = D('Common/Follow', 'Service');
		$map['target_id'] = $uid;
		$map = array_merge($map, $query);
		//start modiby by susy
		//$uids = $service->order('create_time desc')->where($map)->limit($limit)->getField('uid', true);
		$res = $service->order('create_time desc')->where($map)->limit($limit);
		if($page)
			$res->page($page);
		$uids = $res->getField('uid', true);
		//end
		if (!$detail)
		{
			return $uids;
		}
		else
		{
			$uEvent = A('Api/User','Event');
			foreach ($uids as $id) {
				$user = $uEvent->detail($id);
				$user['is_follow'] = $this->is_follow($uid, $id)?1:0;
				$data[] = $user;
			}
			return $data;
		}
	}

	#ACTION

	/** 
	 * 添加关注
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return  
	 */
	
	public function follow($uid, $target_id)
	{
		if (!$uid || !$target_id)
		{
			return;
		}
		$service = D('Common/Follow', 'Service');
		$map['uid']       = intval($uid);
		$map['target_id'] = intval($target_id);
		if (!$service->where($map)->find())
		{	
			$map['create_time'] = NOW_TIME;
			$service->add($map);
			// $sender = get_nickname($uid);
			// $to = get_nickname($target_id);	

			try {
				//更新排行榜
				$Redis = CacheEvent::instance(7);
				$week = date('YW');
				$redis_key = "IMBA.RANK.USER.STAR.WEEK.{$week}";
				// 存活到三周后
				$redis_expire = date('Ymd', strtotime('next Monday +2 week'));

				$exists = $Redis->exists($redis_key);
				$Redis->zIncrBy($redis_key, 1, $target_id);
				!$exists && $Redis->expireAt($redis_key, strtotime($redis_expire));

				// 上报用户操作，用于显示红点
				$params = [
					['uid' => $uid, 'actions' => ['follow']],
					['uid' => $target_id, 'actions' => ['fans']]
				];
				event('LocalClient')->doRequest('reddot', ['data' => json_encode($params)]);
			} catch (\Exception $e) {
				\Think\Log::record('[UPDATE RANK ERROR] - REDIS EXCEPTION - '.$e->getMessage(), 'ERR');
			}

			$sender = [
				'uid' => $uid,
				'nickname' => get_nickname($uid),
			];

			$to = [
				'uid' => $target_id,
				'nickname' => get_nickname($target_id),
			];

			// 添加message数据 liubo 2016-07-13
			event('Message')->send('follow', 0, $uid, $target_id);
			event('Push')->fans($sender, $to);
			return true;
		}
		return false;
	}


	/** 
	 * 取消关注
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function unfollow($uid, $target_id)
	{
		if (!$uid || !$target_id)
		{
			return;
		}
		$map['uid']       = intval($uid);
		$map['target_id'] = intval($target_id);
		$service = D('Common/Follow', 'Service');
		if (!$service->where($map)->find())
		{
			return false;	
		}
		$service->where($map)->delete();
		try {
			//更新排行榜
			$Redis = CacheEvent::instance(7);
			$week = date('YW');
			$redis_key = "IMBA.RANK.USER.STAR.WEEK.{$week}";
			// 存活到三周后
			$redis_expire = date('Ymd', strtotime('next Monday +2 week'));

			$exists = $Redis->exists($redis_key);
			$Redis->zIncrBy($redis_key, -1, $target_id);
			!$exists && $Redis->expireAt($redis_key, strtotime($redis_expire));
		} catch (\Exception $e) {
			\Think\Log::record('[UPDATE RANK ERROR] - REDIS EXCEPTION - '.$e->getMessage(), 'ERR');
		}
		return ture;
	}

	/**
	 * 根据查询条件获取关注或粉丝
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $uid     当前userId
	 * @param  boolean $detail   是否查询用户详细信息
	 * @param  array   $query    其他查询条件
	 * @param  boolean $isFans   粉丝-true, 关注-false
	 * @param  integer $limit    数量
	 * @param  integer $page     页码
	 * @param  string  $keywords 昵称关键字
	 * @return array
	 */
	public function getFollows($uid, $detail = false, $query = array(), $isFans = true, $limit = 10, $page = 1, $keywords) {
		$uid = intval($uid);
		$service = service('Follow');
		if ($isFans) {
			$map['target_id'] = $uid;
			$field = 'uid';
		} else {
			$map['uid'] = $uid;
			$field = 'target_id';
		}
		$query && $map = array_merge($map, $query);

		//用户Id列表
		$res = $service->order('create_time desc')->where($map)->getField($field, true);
		if (!$res) {
			return [];
		}

		$userCondition = [
			'id' => ['in', $res]
		];
		if (!empty($keywords)) {
			$userCondition['nickname'] = ['like', $keywords];
		}
		$userService = service('Users');
		$userList = $userService->where($userCondition)->limit($limit);
		if ($page) {
			$userList->page($page);
		}
		$uids = $userList->getField('id', true);

		if (!$detail) {
			return $uids;
		} else {
			$videoService = service('Video');
			$uEvent = A('Api/User','Event');
			foreach ($uids as $id) {
				$user = $uEvent->detail($id);
				$user['activityCount'] = $videoService->where(['uid' => $id])->count();
				$data[] = $user;
			}
			return $data;
		}
	}

	/**
	 * 根据查询条件获取关注或粉丝总数
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $uid      用户Id
	 * @param  array   $query    其他查询条件
	 * @param  boolean $isFans   粉丝-true, 关注-false
	 * @param  string  $keywords 用户昵称关键字
	 * @return integer
	 */
	public function getFollowsCount($uid, $query = array(), $isFans = true, $keywords = null) {
		$uid = intval($uid);
		$service = service('Follow');
		if ($isFans) {
			$map['target_id'] = $uid;
			$field = 'uid';
		} else {
			$map['uid'] = $uid;
			$field = 'target_id';
		}
		$query && $map = array_merge($map, $query);

		if (empty($keywords)) {
			return $service->order('create_time desc')->where($map)->count();
		}

		//用户Id列表
		$res = $service->order('create_time desc')->where($map)->getField($field, true);

		$userCondition = [
			'id' => ['in', $res]
		];
		if (!empty($keywords)) {
			$userCondition['nickname'] = ['like', $keywords];
		}
		$userService = service('Users');
		return $userService->where($userCondition)->count();
	}
}